<template>
  <div ref="highChartContainer"></div>
</template>

<script>
import { computed, defineComponent, onUnmounted, watch, watchEffect } from 'vue'
import * as Highcharts from 'highcharts';
import stockInit from 'highcharts/modules/stock'
import GlobalData from '@/store/index'
export default defineComponent({
  props: {
    options: {
      type: Object,
    },
    chartType: {
      type: String,
      default: () => 'normal'
    }
  },
  setup(props, { attrs, slots, emit }) {
    const randomString = (length) => {
      var str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
      var result = '';
      for (var i = length; i > 0; --i)
        result += str[Math.floor(Math.random() * str.length)];
      return result;
    }

    const uid = `hight-chart-${randomString(6)}`


    const DEFAULT_OPTIONS = {
      credits:{
        enabled: false // 禁用版权信息
      },
    }

    const getChartInstance = () => {
      const chartTypeMapping = {
        normal: () => Highcharts.chart,
        stock: () => {
          stockInit(Highcharts)
          return Highcharts.stockChart
        },
      }
      const chartInstance =
        chartTypeMapping[props.chartType]
          || chartTypeMapping.normal
      return chartInstance()
    }

    const chartInstance = getChartInstance()

    GlobalData.onMenuCollapse(() => {
      setTimeout(() => {
        let myEvent = new Event('resize');
        window.dispatchEvent(myEvent);
      }, 100)
    }, uid)
    onUnmounted(() => {
      GlobalData.menuCollapseHookRemove(uid)
    })

    const render = () => {
      chartInstance(uid,
        Object.assign(DEFAULT_OPTIONS, props.options)
      )
    }

    return {
      uid,
      DEFAULT_OPTIONS,
      render,
      ...props,
    }

  },
  watch: {
    options: {
      handler() {
        this.render()
      },
      deep: true
    }
  },
  mounted() {
    const container = this.$refs.highChartContainer
    container.id = this.uid
    this.render()
  }
})
</script>

<style lang="scss" scoped>

</style>
